package main.UI;

import main.database.DatabaseException;
import main.database.SQLDatabaseManager;
import main.database.entity.Category;
import main.database.entity.MyEntity;
import main.database.entity.Product;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.awt.event.*;
import java.util.Enumeration;
import java.util.List;

public class SelectEntryDialog extends JDialog{
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTree treeList;

    private String item = "";
    private boolean canSelectCategory;
    //@Params
    //dontAddProducts - if 'true' leaves out all products from tree

    //TODO Maybe make different icon for categories
    public SelectEntryDialog(boolean withProducts, boolean canSelectCategory) throws DatabaseException {
        this.canSelectCategory = canSelectCategory;
        setModalityType(DEFAULT_MODALITY_TYPE);
        setTitle("Выбор продукта");
        setContentPane(contentPane);
        getRootPane().setDefaultButton(buttonOK);

        DefaultMutableTreeNode top = new DefaultMutableTreeNode("Продукты");
        top.add(new DefaultMutableTreeNode("Все"));
        top.add(new DefaultMutableTreeNode(Category.NO_CATEGORY_WITH_TAGS));
        DefaultTreeModel model = new DefaultTreeModel(top);
        treeList.setModel(model);


        SQLDatabaseManager mngr = GUI.getSQLManager();

            List categoryList = mngr.getAllEntriesFromDB(MyEntity.CATEGORY);
        for (Object aCategory : categoryList) {
            Category cat = (Category) aCategory;
            addCategoryBranch(cat.getName());
        }

        if (withProducts) {
            List productList = mngr.getAllEntriesFromDB(MyEntity.PRODUCT);
            for (Object aProduct : productList) {
                Product product = (Product) aProduct;

                String categoryName;
                if (product.getCategory() == null)
                    categoryName = Category.NO_CATEGORY;
                else
                    categoryName = product.getCategory().getName();
                addProductLeaf(product.getName(), categoryName);
            }
        }
        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }


    private void onOK() {
        if(!saveChoice())
            return;
        dispose();
    }

    private void onCancel() {
        dispose();
    }

    private void addCategoryBranch(String name) {
        DefaultMutableTreeNode category = new DefaultMutableTreeNode(name);
        DefaultMutableTreeNode all = (DefaultMutableTreeNode)
                ((DefaultMutableTreeNode) treeList.getModel().getRoot()).getFirstChild();
        all.add(category);
    }

    private void addProductLeaf(String name, String category) {
        Enumeration<?> firstLevelNodes
                = ((DefaultMutableTreeNode) treeList.getModel().getRoot()).getFirstChild().children();

        if (category.equals(Category.NO_CATEGORY))  {
            DefaultMutableTreeNode noCategory = (DefaultMutableTreeNode)
                    ((DefaultMutableTreeNode) treeList.getModel().getRoot()).getLastChild();
            noCategory.add(new DefaultMutableTreeNode(name));
        }

            while (firstLevelNodes.hasMoreElements()) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) firstLevelNodes.nextElement();
                if (node.toString().equals(category)) {
                    node.add(new DefaultMutableTreeNode(name));
                    break;
                }
            }
    }

    private boolean saveChoice() {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) treeList.getLastSelectedPathComponent();
        //If we can't select category and node parent is root or "All" node (which all categories are) - return false.
        if (!canSelectCategory && (node.getParent().toString().equals("Все") ||
                (((DefaultMutableTreeNode) node.getParent()).isRoot())))
            return false;
        if (node.toString().equals(Category.NO_CATEGORY_WITH_TAGS))
            item = Category.NO_CATEGORY;
        else
            item = node.toString();
        return true;
    }

    public String getItem() {
         return item;
    }

}
